<!-- @module travel-form -->
<!-- @author: YunTao.Li -->
<!-- @description:  出差单form组件-->
<!-- @since: 2019-11-19 12:47:36 -->
<template>
  <div class="app-container">
    <fieldset class="fieldset" style="margin-top:0px;">
      <legend class="legend-font" v-text="form_title" />
      <el-form ref="travelInputForm" :model="travelInputForm" :label-position="labelPosition" :rules="formFormatRules" label-width="120px" size="mini">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="组织机构" prop="orgCode">
              <!-- <el-input v-model="travelInputForm.ouId" name="ouId" placeholder="组织机构" /> -->
              <OrgSelectTree ref="orgSelectRef" v-model="travelInputForm.orgCode" placeholder="组织机构" :disabled="true" @bindLabel="bindLabel" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="组织部门" prop="deptName">
              <el-input v-model="travelInputForm.deptName" name="deptName" placeholder="组织部门" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="申请人" prop="createdBy">
              <EmpCombobox v-model="travelInputForm.empName" name="empName" placeholder="申请人" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="申请单编码" prop="bizTravelCode">
              <el-input v-model="travelInputForm.bizTravelCode" name="bizTravelCode" placeholder="保存后自动生成" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker v-model="travelInputForm.startDate" :picker-options="pickerOptionsStart" style="width:100%;" type="date" name="startDate" placeholder="开始日期" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="开始时段" prop="startTimeType">
              <!-- <el-input v-model="travelInputForm.startTimeType" name="startTimeType" placeholder="开始时段" /> -->
              <dictCombo v-model="travelInputForm.startTimeType" dicttypeid="timeType" name="startTimeType" placeholder="开始时段" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="travelInputForm.endDate" :picker-options="pickerOptionsEnd" style="width:100%;" type="date" name="endDate" placeholder="结束日期" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="结束时段" prop="endTimeType">
              <!-- <el-input v-model="travelInputForm.endTimeType" name="endTimeType" placeholder="结束时段" /> -->
              <dictCombo v-model="travelInputForm.endTimeType" dicttypeid="timeType" name="endTimeType" placeholder="结束时段" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="交通工具" prop="traffic">
              <!-- <el-input v-model="travelInputForm.traffic" name="traffic" placeholder="交通工具" /> -->
              <dictCombo v-model="travelInputForm.traffic" dicttypeid="traffic" name="traffic" placeholder="交通工具" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="返回交通工具" prop="backTraffic">
              <!-- <el-input v-model="travelInputForm.backTraffic" name="backTraffic" placeholder="返回交通工具" /> -->
              <dictCombo v-model="travelInputForm.backTraffic" dicttypeid="traffic" name="traffic" placeholder="交通工具" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="出差天数" prop="days">
              <el-input v-model="travelInputForm.days" name="days" placeholder="出差天数" :disabled="true" />
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="实际天数" prop="actualDays">
              <el-input v-model="travelInputForm.actualDays" name="actualDays" placeholder="实际天数" :disabled="true" />
            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <el-form-item label="出差路线" prop="trace">
              <el-input v-model="travelInputForm.trace" name="trace" placeholder="出差路线" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="出差待办事由" prop="travelDesc">
              <el-input v-model="travelInputForm.travelDesc" style="width:80%" type="textarea" rows="2" name="travelDesc" placeholder="出差待办事由" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </fieldset>

    <!-- 随同人员 begin-->
    <fieldset class="fieldset" style="margin-top:5px;">
      <!--button-->
      <div class="div-button" style="margin-top:10px;">
        <el-button
          icon="el-icon-menu"
          type="success"
          size="mini"
          @click="onOpenEmpDialog"
        >选择人员</el-button>
      </div>
      <legend class="legend-font" v-text="travel_emp_text" />
      <div class="div-table">
        <el-table ref="travelEmpTable" :data="travelInputForm.bizTravelEmpList" :v-model="travelInputForm.bizTravelEmpList" border fit highlight-current-row style="width: 100%" max-height="250" size="mini">
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" width="55" label="序号" />
          <!--员工名称-->
          <el-table-column align="center" label="员工名称" width="200px" prop="empName">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.empName" size="mini" placeholder="员工名称" /> -->
              <span>{{ scope.row.empName }}</span>
            </template>
          </el-table-column>
          <!--员工ID-->
          <el-table-column align="center" label="员工编码" width="150px" prop="empId">
            <template slot-scope="scope">
              <span>{{ scope.row.empId }}</span>
            </template>
          </el-table-column>
          <!--开始日期-->
          <el-table-column width="150px" align="center" label="开始日期" prop="startDate">
            <template slot-scope="scope">
              <span>{{ scope.row.startDate | parseTime('{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <!--开始时段-->
          <el-table-column width="150px" align="center" label="开始时段" prop="startTimeType">
            <template slot-scope="scope">
              <span>{{ scope.row.startTimeType }}</span>
            </template>
          </el-table-column>
          <!--结束日期-->
          <el-table-column width="150px" align="center" label="结束日期" prop="endDate">
            <template slot-scope="scope">
              <span>{{ scope.row.endDate | parseTime('{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <!--结束时段-->
          <el-table-column width="150px" align="center" label="结束时段" prop="endTimeType">
            <template slot-scope="scope">
              <span>{{ scope.row.endTimeType }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template scope="scope">
              <el-button size="small" type="danger" @click="onDelEmp(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </fieldset>
    <!-- 随同人员 end-->
    <fileUpload :param-pa-doc-id="travelInputForm.fileParamPaDocId" />

    <div slot="footer" class="dialog-footer" style="margin:10px;text-align: center">
      <el-button @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </div>

    <!--选择员工dialog-->
    <el-dialog title="选择人员列表" :visible.sync="empDialogVisible" width="50%" top="5vh" append-to-body :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <!-- table begin-->
      <div class="div-table">
        <fieldset class="fieldset" style="margin-top:15px;">
          <legend class="legend-font" v-text="dialog_title_emp" />
          <el-table ref="empListTable" :data="chooseEmpList" border fit highlight-current-row style="width: 100%" max-height="250" size="mini">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="100" label="序号" />
            <!--员工编码-->
            <el-table-column align="center" label="员工编码" width="200px">
              <template slot-scope="scope">
                <span>{{ scope.row.empId }}</span>
              </template>
            </el-table-column>
            <!--员工姓名-->
            <el-table-column align="center" label="员工姓名" width="200px">
              <template slot-scope="scope">
                <span>{{ scope.row.empName }}</span>
              </template>
            </el-table-column>
          </el-table>
        </fieldset>
      </div>
      <pagination v-show="emptotal>0" :total="emptotal" :page.sync="empQueryForm.page" :limit.sync="empQueryForm.limit" @pagination="onLoadEmpList" />
      <div slot="footer" class="dialog-footer" style="margin:10px;text-align: center">
        <el-button size="mini" @click="onCancelEmp">取 消</el-button>
        <el-button type="primary" size="mini" @click="onChooseEmp">选择</el-button>
      </div>

    </el-dialog>
    <!--选择员工dialog end-->
  </div>
</template>

<script>
import dictCombo from './../combo/dict-comb'
import { travelEmps } from '@/api/attendance/travel-service'
import { getEmpList } from '@/api/organization/emp-service'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import fileUpload from './../fileupload'
import { createUniqueString } from '@/utils'
import OrgSelectTree from './../combo/org-tree-select.vue'
import EmpCombobox from '@/views/attendance/components/combo/emp-comb'
import { dateCalc } from '@/api/attendance/holidaylaws-service'
import { travelAdd } from '@/api/attendance/travel-service'

export default {
  components: { dictCombo, Pagination, fileUpload, OrgSelectTree, EmpCombobox },
  data() {
    return {
      formDataEdit: false,
      dialogFormVisible: false,
      empDialogVisible: false,
      labelPosition: 'right',
      form_title: '起草出差申请单',
      travel_emp_text: '随同人员',
      dialog_title_emp: '选择人员',
      btn_emp_del_disabled: false,
      emptotal: 0,
      empQueryForm: {
        page: 1,
        limit: 10,
        empCode: '',
        empName: ''
      },
      travelInputForm: {
        fileParamPaDocId: '',
        bizTravelId: '',
        ouId: '',
        orgCode: '',
        orgName: '',
        deptId: '',
        deptCode: '',
        deptName: '',
        empCode: '',
        empName: '',
        createdBy: '',
        startDate: null,
        startTimeType: '',
        endDate: null,
        endTimeType: '',
        traffic: '',
        backTraffic: '',
        days: '',
        bizTravelCode: '',
        actualDays: '',
        trace: '',
        travelDesc: '',
        bizTravelEmpList: [{
          empName: '',
          empId: '',
          empCode: '',
          startDate: '',
          startTimeType: '',
          endTimeType: ''
        }]
      },
      pickerOptionsStart: {
        disabledDate: (time) => {
          if (this.travelInputForm.endDate) {
            return time.getTime() > new Date(this.travelInputForm.endDate).getTime() - 1 * 24 * 60 * 60 * 1000
          }
          return false
        }
      },
      pickerOptionsEnd: {
        disabledDate: (time) => {
          return time.getTime() < new Date(this.travelInputForm.startDate).getTime() + 1 * 24 * 60 * 60 * 1000
        }
      },
      chooseEmpList: [{
        empId: '',
        empCode: '',
        empName: ''
      }],
      dateCalcQuery: {
        startDate: null,
        startTimeType: '',
        endDate: null,
        endTimeType: ''
      },
      formFormatRules: {
        orgCode: [{
          required: true,
          message: '组织机构不能为空',
          trigger: 'blur'
        }],
        createdBy: [{
          required: true,
          message: '申请人不能为空',
          trigger: 'blur'
        }],
        startDate: [{
          required: true,
          message: '开始日期不能为空',
          trigger: 'blur'
        }],
        startTimeType: [{
          required: true,
          message: '开始时段不能为空',
          trigger: 'blur'
        }],
        endDate: [{
          required: true,
          message: '结束日期不能为空',
          trigger: 'blur'
        }],
        endTimeType: [{
          required: true,
          message: '结束时段不能为空',
          trigger: 'blur'
        }],
        traffic: [{
          required: true,
          message: '交通工具不能为空',
          trigger: 'blur'
        }],
        backTraffic: [{
          required: true,
          message: '返回交通工具不能为空',
          trigger: 'blur'
        }]
      },
      formLabelWidth: '120px'
    }
  },
  computed: {
    cmp_startDate() {
      return this.travelInputForm.startDate
    },
    cmp_startTimeType() {
      return this.travelInputForm.startTimeType
    },
    cmp_endDate() {
      return this.travelInputForm.endDate
    },
    cmp_endTimeType() {
      return this.travelInputForm.endTimeType
    },
    cmp_traffic() {
      return this.travelInputForm.traffic
    },
    cmp_backTraffic() {
      return this.travelInputForm.backTraffic
    },
    cmp_trace() {
      return this.travelInputForm.trace
    },
    cmp_travelDesc() {
      return this.travelInputForm.travelDesc
    },
    cmp_bizTravelEmpList() {
      return this.travelInputForm.bizTravelEmpList
    }
  },
  watch: {
    cmp_startDate(newValue, oldValue) {
      this.daysCalc()
      this.formDataEdit = true
    },
    cmp_startTimeType(newValue, oldValue) {
      this.daysCalc()
      this.formDataEdit = true
    },
    cmp_endDate(newValue, oldValue) {
      this.daysCalc()
      this.formDataEdit = true
    },
    cmp_endTimeType(newValue, oldValue) {
      this.daysCalc()
      this.formDataEdit = true
    },
    cmp_traffic(newValue, oldValue) {
      this.formDataEdit = true
    },
    cmp_backTraffic(newValue, oldValue) {
      this.formDataEdit = true
    },
    cmp_trace(newValue, oldValue) {
      this.formDataEdit = true
    },
    cmp_travelDesc(newValue, oldValue) {
      this.formDataEdit = true
    },
    cmp_bizTravelEmpList(newValue, oldValue) {
      // this.formDataEdit = true
    }
  },
  created() {
    const uuid = createUniqueString()
    this.travelInputForm.fileParamPaDocId = uuid
    this.travelInputForm.bizTravelEmpList.splice(0, this.travelInputForm.bizTravelEmpList.length)
  },
  mounted() {
    try {
      this.travelInputForm.empCode = localStorage.getItem('empCode')
      this.travelInputForm.empName = localStorage.getItem('empName')
      this.travelInputForm.deptName = localStorage.getItem('deptName')
      this.travelInputForm.deptCode = localStorage.getItem('deptCode')
      this.travelInputForm.orgCode = localStorage.getItem('orgCode')
    } catch (e) {
      console.log(e)
    }
  },
  methods: {
    bindLabel(orgId, label) {
      if (orgId && orgId !== '') {
        this.travelInputForm.ouId = orgId
      }

      if (label && label !== '') {
        this.travelInputForm.orgName = label
      }
    },
    daysCalc() {
      this.dateCalcQuery.startDate = this.travelInputForm.startDate
      this.dateCalcQuery.startTimeType = this.travelInputForm.startTimeType
      this.dateCalcQuery.endDate = this.travelInputForm.endDate
      this.dateCalcQuery.endTimeType = this.travelInputForm.endTimeType

      if (this.dateCalcQuery.startDate && this.dateCalcQuery.startTimeType && this.dateCalcQuery.endDate && this.dateCalcQuery.endTimeType) {
        dateCalc(this.dateCalcQuery).then(response => {
          const data = response.data
          this.travelInputForm.days = data.workDay
          this.travelInputForm.actualDays = data.natureDay
        })
      } else {
        console.log('value null')
      }
    },
    onSubmit() { // 保存
      var _this = _this || this
      this.$refs.travelInputForm.validate((valid) => {
        if (valid) {
          travelAdd(this.travelInputForm).then(response => {
            if (response.code === 200) {
              _this.$message({ type: 'success', message: '起草因公外出申请成功!' })
              setTimeout(() => {
                _this.$router.go(-1)
              }, 500)
            } else {
              this.$message.error(response.message)
            }
          })
        } else {
          return false
        }
      })
    },
    onDelEmp(index, row) {
      this.travelInputForm.bizTravelEmpList.splice(index, 1)
    },
    onLoadTravelEmps(travelId) {
      travelEmps(travelId).then(response => {
        this.travelInputForm.bizTravelEmpList = response.data
      })
    },
    // emp dialog function betin*****************************************
    onOpenEmpDialog() { // 打开人员选择框
      this.$refs.travelInputForm.validate((valid) => {
        if (valid) {
          this.empDialogVisible = true
          // 查询随行人员
          this.onLoadEmpList()
        } else {
          return false
        }
      })
    },
    onLoadEmpList() {
      getEmpList(this.empQueryForm).then(response => {
        this.chooseEmpList = response.data.records
      })
    },
    onCancel() {
      var _this = _this || this
      console.log('_this.formDataEdit : ' + _this.formDataEdit)
      if (_this.formDataEdit) {
        _this.$confirm('数据未保存，确认放弃因公外出申请?', '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          window.history.go(-1)
        }).catch(err => {
          // console.error(err)
          console.log(err)
        })
      } else {
        window.history.go(-1)
      }
    },
    onCancelEmp() {
      this.empDialogVisible = false
    },
    onChooseEmp() {
      this.empDialogVisible = false

      const selectedData = this.$refs.empListTable.selection
      var selectedDataLength = selectedData.length

      // 构造form对象用于填充人员信息
      const formStartDate = this.travelInputForm.startDate
      const formStartTimeType = this.travelInputForm.startTimeType
      const formEndDate = this.travelInputForm.endDate
      const formEndTimeType = this.travelInputForm.endTimeType

      // 循环填充
      while (selectedDataLength--) {
        const currentData = selectedData[selectedDataLength]

        const travelEmpInfo = {
          empId: currentData.empCode,
          empName: currentData.empName,
          startDate: formStartDate,
          startTimeType: formStartTimeType,
          endDate: formEndDate,
          endTimeType: formEndTimeType
        }
        this.travelInputForm.bizTravelEmpList.push(travelEmpInfo)
      }
    }
  }
}
</script>

<style>
/* .el-date-picker{
  width: 80%
} */

</style>
